package com.xbongbong.paas.help.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.abstracts.AbstractOperatorFieldHandler;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.help.factory.OperatorFieldHandler;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.OperationsPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2020/3/4 21:11
 * @since v1.0
 */
@Component
public class OperatorNumHandlerImpl extends AbstractOperatorFieldHandler {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.NUM.getType());
    }

    @Override
    public Object handlerThisFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity, BusinessRuleInfoPojo businessRuleInfoPojo) throws XbbException {
        // 无法特殊处理
        Object num = data.get(fieldAttrEntity.getAttr());
        if (Objects.isNull(num)) {
            return 0;
        }
        return num;
    }

    @Override
    public Object handlerTargetFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity, FieldAttrEntity targetField,
                                         BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        if (Objects.isNull(businessRuleInfoPojo.getObject())) {
            Object num = data.get(fieldAttrEntity.getAttr());
            if (Objects.isNull(num)) {
                return 0;
            }
            return num;
        }
        // 直接将当前表单的数据赋值给目标表单，无需进行精度计算；
        return businessRuleInfoPojo.getObject();
    }

    @Override
    public Object handlerFixedValue(FieldAttrEntity targetField, BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        Object object = operation.getValue();
        if (object instanceof String && RegexUtil.isNumber(object.toString())) {
            // 对字符串的数字或者浮点型进行强制转换
            if (object.toString().contains("\\.")) {
                return Double.valueOf(operation.getValue().toString());
            } else {
                return Long.valueOf(object.toString());
            }
        }
        // 如果是非数字类型，不进行加减
        if (!(object instanceof Number)) {
            throw new XbbException(ProErrorCodeEnum.API_ERROR_260017);
        }
        return object;
    }
}
